﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Utility
{
    public static class JsonExtension
    {
        /// <summary>
        /// json转实体
        /// </summary>
        /// <param name="Json"></param>
        /// <returns></returns>
        public static object ToJson(this string Json)
            => Json is null ? null : JsonConvert.DeserializeObject(Json);


        /// <summary>
        /// 实体转json
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToJson(this object obj)
            => JsonConvert.SerializeObject(obj, new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });



        /// <summary>
        /// json转实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Json"></param>
        /// <returns></returns>
        public static T ToObject<T>(this string Json)
            => Json is null ? default(T) : JsonConvert.DeserializeObject<T>(Json);


        /// <summary>
        /// json转list<t>集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Json"></param>
        /// <returns></returns>
        public static List<T> ToList<T>(this string Json)
            => Json is null ? default(List<T>) : JsonConvert.DeserializeObject<List<T>>(Json);
  

        /// <summary>
        /// json转datatable
        /// </summary>
        /// <param name="Json"></param>
        /// <returns></returns>
        public static DataTable ToTable(this string Json)
            => Json is null ? default(DataTable) : JsonConvert.DeserializeObject<DataTable>(Json);


        /// <summary>
        /// json转jobject
        /// </summary>
        /// <param name="Json"></param>
        /// <returns></returns>
        public static JObject ToJObject(this string Json)
            => Json is null ? JObject.Parse("{}") : JObject.Parse(Json.Replace("&nbsp;", ""));
            
    }
}
